﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MLM.Data;
using MLM.Base;

namespace MLM.AdminCP.Pages
{
    public partial class IncommingProductOrderDetail : BasePage
    {
        public static MLMDataContext dtct = new MLMDataContext();
       
        protected void Page_Load(object sender, EventArgs e)
        {
           // Permission.CheckIsAdmin();
            MLMDataContext ct = new MLMDataContext();
            long InvoiceID = long.Parse(Request.QueryString["ID"]);
            var status = ct.Invoices.FirstOrDefault(it => it.InvoiceID == InvoiceID).Status;
           // PanelChangeStatus.Visible = status == -1;
            SaveChangeStatus.Click += new EventHandler(SaveChangeStatus_Click);
        }

        void SaveChangeStatus_Click(object sender, EventArgs e)
        {
            MLMDataContext ct = new MLMDataContext();
            long InvoiceID = long.Parse(Request.QueryString["ID"]);
            var invoice = ct.Invoices.FirstOrDefault(it => it.InvoiceID == InvoiceID);
            invoice.Status = int.Parse(StatusSelect.SelectedValue);
            ct.SaveChanges();
            if (invoice.Status==1)
            {
                IQueryable<InvoiceDetail> invoiceDetails = ct.InvoiceDetails.Where(it => it.InvoiceID == InvoiceID);
                foreach (var invoiceDetail in invoiceDetails)
                {
                    if (ct.UserStocks.FirstOrDefault(it => it.ProductBaseID == invoiceDetail.ProductBaseID && it.UserID == invoice.UserID) != null)
                    {
                        ct.UserStocks.FirstOrDefault(it => it.ProductBaseID == invoiceDetail.ProductBaseID && it.UserID == invoice.UserID).StockAvaiable +=
                            invoiceDetail.Quantity;
                    }
                    else
                    {
                        ct.UserStocks.AddObject(new UserStock
                        {
                            IsShowOnShop = true,
                            ProductBaseID = invoiceDetail.ProductBaseID,
                            StockAvaiable = invoiceDetail.Quantity,
                            UserID = invoice.UserID
                        });
                    }
                    if (Permission.GetUserRole(ct, invoice.DepoID) != 1)
                    {
                        ct.UserStocks.FirstOrDefault(
                           it => it.UserID == invoice.DepoID && it.ProductBaseID == invoiceDetail.ProductBaseID).StockAvaiable
                           -= invoiceDetail.Quantity;
                    }
                }
                ct.SaveChanges();
            }
            
            Response.Redirect(Request.RawUrl);
        }
    }
}